package com.chixing.controller;

import com.chixing.commons.DataGridViewResult;
import com.chixing.commons.Result;
import com.chixing.commons.ServerResponse;
import com.chixing.commons.TokenUtil;
import com.chixing.config.CookieUtils;
import com.chixing.pojo.*;
import com.chixing.service.ICompanyManageService;
import com.chixing.service.IJobDetailService;

import com.chixing.service.IMycollectsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 职位详情表 前端控制器
 * </p>
 *
 * @author Jason Marslyon
 * @since 2022-10-04
 */
@RestController

public class JobDetailController {
@Autowired
private IMycollectsService mycollectsService;
    @Autowired
private IJobDetailService jobDetailService;
    @Autowired
    private ICompanyManageService companyManageService;
    @GetMapping("job/{id}")
    public ModelAndView testSelect(@PathVariable("id")int jobId){
        ServerResponse res=jobDetailService.selectJob(jobId);
        ModelAndView mav=new ModelAndView();
        mav.addObject("res",res);
        mav.setViewName("public/Job/SearchJob");
        return mav;


    }
//不筛选的分页
    @GetMapping("job/getAll/{pageNum}")
    public ServerResponse getAlljob(@PathVariable("pageNum") Integer pageNum,HttpSession session){
        System.out.println("------------"+pageNum);


        ServerResponse result=jobDetailService.selectAllJobs(pageNum);
        session.setAttribute("jobCompany",result.getData());
        return result;
    }

//职位筛选的分页
    @PostMapping("job/getAlls/{pageNum}")
   public ServerResponse getAll(@PathVariable("pageNum") Integer pageNum,HttpSession session,String companyIndustry,String jobDegree,String salary,String jingyan,String companyScale){
        System.out.println("++++++++++++++"+pageNum);
        ServerResponse result=jobDetailService.selectAllJob(pageNum,companyIndustry,jobDegree,salary,jingyan,companyScale);
        session.setAttribute("jobCompany",result.getData());
        return result;
    }
    //跳转单个职位的详情页面
    @GetMapping("job/getById/{jobId}")
    public ModelAndView getById(@PathVariable("jobId") int jobId){
        ServerResponse result=jobDetailService.getJobDetail(jobId);

        ServerResponse manager=companyManageService.getManagerMsg(jobId);
        ModelAndView mav=new ModelAndView();
        mav.addObject("result",result);
        mav.addObject("resultmanager",manager);
        mav.setViewName("public/Job/JobDetail");
        return mav;
    }
    //筛选的职位总数
    @PostMapping("job/getTotal")
    public ServerResponse getTotal(String companyIndustry,String jobDegree,String salary,String jingyan,String companyScale){

        ServerResponse result=jobDetailService.getJobTotal(companyIndustry,jobDegree,salary,jingyan,companyScale);
        return result;
    }


//不筛选的职位总数
    @GetMapping("job/getTotals")
    public ServerResponse getTotal(){
        ServerResponse result=jobDetailService.getJobTotals();
        return result;
    }
//点击收藏到收藏页面  发送jobId
    @PostMapping("job/sendToCollect")
    public ServerResponse sendToCollect(Integer jobId, String token){

        ServerResponse result = mycollectsService.saveCollection(jobId, token);
        return result;

    }


    //模糊搜索的总条数
    @PostMapping("job/getConfuseNum")
    public ServerResponse getConfuseNum(String kw){
        ServerResponse result = jobDetailService.selectConfuseNum(kw);
        return result;
    }
    //模糊搜索
    @PostMapping("job/getConfuseJob/{pageNum}")
    public ServerResponse getConfuseJob(String kw,@PathVariable("pageNum")Integer pageNum){
        ServerResponse result = jobDetailService.selectConfuseJob(kw,pageNum);
        return result;
    }
    //存入cookie中
    @PostMapping("job/saveInCookie")
    public String saveInCookie(String token,Integer jobId, HttpServletRequest request, HttpServletResponse response){
        System.out.println("*******************************444444444444444444444********************************************"+jobId);
        Cookie[] cookies=request.getCookies();
        String jobIds="";
        String job=String.valueOf(jobId);
        if (token==null){
            String[] str=jobIds.split("#");
            if (str.length>4){
                jobIds=jobIds.substring(0,jobIds.lastIndexOf("#"));
                jobIds=job+"#"+jobIds;
                Cookie cookie=new Cookie("user",jobIds);
//                cookie.setDomain("localhost");
                cookie.setPath("/");
                response.addCookie(cookie);
            }else{
                jobIds+=job;
                Cookie cookie=new Cookie("user",jobIds);

                cookie.setPath("/");
                response.addCookie(cookie);
            }
        }
        else {
            LoginPerson loginPerson = TokenUtil.parseToken(token);
            Integer personId = loginPerson.getPersonId();
            String perId=String.valueOf(personId);
            Cookie cookie= CookieUtils.getCookie(cookies,perId);
            if (null!=cookie){
                jobIds=cookie.getValue();

                if (jobIds.indexOf("#")>0){
                    //判断是否重复
                    String[] str=jobIds.split("#");
                    boolean flag=false;
                    for (String s:str){
                        if (s.equals(job)){
                            flag=true;
                            break;
                        }
                    }
                    if (!flag){
                        if (str.length>4){
                            jobIds=jobIds.substring(0,jobIds.lastIndexOf("#"));
                            jobIds=job+"#"+jobIds;
                            cookie=new Cookie(perId,jobIds);

                            cookie.setPath("/");
                            response.addCookie(cookie);
                        }
                        else{
                            jobIds=job+"#"+jobIds;
                            cookie=new Cookie(perId,jobIds);

                            cookie.setPath("/");
                            response.addCookie(cookie);
                        }
                    }
                }
                //刚登录，什么都没看
                else{
                    if (!jobIds.equals(job)){
                        jobIds=job+"#"+jobIds;
                        cookie=new Cookie(perId,jobIds);

                        cookie.setPath("/");
                        response.addCookie(cookie);
                    }
                }

            }
            //从来没登陆过，需要新建cookie，放进cookie集合
            else{
                cookie=new Cookie(perId,job);

                cookie.setPath("/");
                response.addCookie(cookie);
            }

        }
        System.out.println("ooooooooooooooooooooooooooooooooooooooooooo"+jobIds);
        return jobIds;
    }

    //获取cookie
    @PostMapping("job/getCookie")
    public ServerResponse getCookieJob(String token,HttpServletRequest request, HttpServletResponse response){
        List<EsJobCompany> list=new ArrayList<>();
        Cookie[] cookies=request.getCookies();
        if(token!=null){
            LoginPerson loginPerson = TokenUtil.parseToken(token);
            String perId=String.valueOf(loginPerson.getPersonId());
            Cookie cookie=CookieUtils.getCookie(cookies,perId);
            String values=cookie.getValue();
            String[] str=values.split("#");
            for (String id:str){
                JobDetail job = jobDetailService.getJob(Integer.valueOf(id));
                CompanyDetail companyDetail = jobDetailService.getCompany(job.getCompanyId());
                EsJobCompany esJobCompany=new EsJobCompany();
                esJobCompany.setJobType(job.getJobType());
                esJobCompany.setJobId(job.getJobId());
                esJobCompany.setCompanyImg(companyDetail.getCompanyImg());
                esJobCompany.setJobName(job.getJobName());
                esJobCompany.setCompanyScale(companyDetail.getCompanyScale());
                esJobCompany.setCompanyName(companyDetail.getCompanyName());
                esJobCompany.setCompanyFinance(companyDetail.getCompanyFinance());
                esJobCompany.setJobExperience(job.getJobExperience());
                esJobCompany.setJobMinSalary(job.getJobMinSalary());
                esJobCompany.setJobMaxSalary(job.getJobMaxSalary());
                esJobCompany.setCompanyId(companyDetail.getCompanyId());
                esJobCompany.setJobLocArea(job.getJobLocArea());
                esJobCompany.setCompanyIndustry(esJobCompany.getCompanyIndustry());
                esJobCompany.setJobDegree(job.getJobDegree());
                list.add(esJobCompany);
            }
        }
        else{
            return ServerResponse.success("fail",new ArrayList<>());
        }
        return ServerResponse.success("***",list);
    }

    //随机显示指定数量的job
    @PostMapping("job/getJobCom")
    public ServerResponse getJobCom(int size){
        ServerResponse result = jobDetailService.getNumJob(size);
        return  result;
    }



    //后台

    @RequestMapping("backStageJobDetail/list")
    public DataGridViewResult list(JobDetailVo jobDetailVo, HttpSession httpSession){
        PageHelper.startPage(jobDetailVo.getPage(),jobDetailVo.getLimit());
        List<JobDetail> jobDetails = jobDetailService.selectAllByPage(jobDetailVo,httpSession);
        PageInfo<JobDetail> pageInfo = new PageInfo<>(jobDetails);
        return new DataGridViewResult(pageInfo.getTotal(),pageInfo.getList());
    }

    @RequestMapping("backStageJobDetail/personList")
    public DataGridViewResult personList(JobDetailVo jobDetailVo, HttpSession httpSession){
        PageHelper.startPage(jobDetailVo.getPage(),jobDetailVo.getLimit());
        List<JobDetail> jobDetails = jobDetailService.selectAllByPagePerson(jobDetailVo,httpSession);
        PageInfo<JobDetail> pageInfo = new PageInfo<>(jobDetails);
        return new DataGridViewResult(pageInfo.getTotal(),pageInfo.getList());
    }

    @RequestMapping("backStageJobDetail/save")
    public Result save(JobDetail jobDetail){
        Boolean aBoolean = jobDetailService.savaJob(jobDetail);
        if(aBoolean){
            return new Result(20000,"添加成功");
        }
        return new Result(20001,"添加失败");
    }

    @RequestMapping("backStageJobDetail/update")
    public Result update(JobDetail jobDetail){
        Boolean aBoolean = jobDetailService.updateJob(jobDetail);
        if(aBoolean){
            return new Result(20000,"修改成功");
        }
        return new Result(20001,"修改失败");
    }

    @RequestMapping("backStageJobDetail/delete")
    public Result delete(Integer id){
        Boolean aBoolean = jobDetailService.deleteJob(id);
        if(aBoolean){
            return new Result(20000,"删除成功");
        }
        return new Result(20001,"删除失败");
    }

    @RequestMapping("backStageJobDetail/selectById")
    public Result selectById(Integer id){
        JobDetail jobDetail = jobDetailService.selectById(id);
        if(jobDetail!=null){
            return new Result(20000,"查询成功");
        }
        return new Result(20001,"没有该用户");
    }


}
